package com.healthy.controller.pc;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.healthy.entity.YgAdmins;
import com.healthy.entity.YgUsers;
import com.healthy.service.YgAdminsService;
import com.healthy.service.YgUsersService;
import com.healthy.util.EncryptUtil;
import com.healthy.validator.Validator;



/**
 * controller 控制层的实现
 * @author HGB丶阳光
 * PC端 YgUsersControllerImpl
 */

@Controller
public class YgUsersControllerImpl {

	@Autowired
	private YgUsersService userService;
	@Autowired
	private YgAdminsService adminService;
	
	/*
	 * 用户模块功能二、用户登出
	 */
	@RequestMapping(value ="/pc/loginout",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject loginout(HttpSession session) {
		// 实例化JSONObject对象
		JSONObject json = new JSONObject();
		int status = 0;
		String msg = "操作失败，请稍后再试";
		System.out.println("之前，session测试："+session.toString());
		session.invalidate();
		status = 1;
		msg = "退出成功";
		json.put("status", status);
		json.put("msg", msg);
		return json;
	}
	
	/*
	 * 用户模块功能一、普通用户登录
	 */
	@RequestMapping(value ="/pc/login",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject login(@RequestBody Map<String,Object> map,HttpSession session){
		System.out.println("map:"+map);
		String username = (String) map.get("username");
		String password = (String) map.get("password");
		JSONObject json=new JSONObject();
		int status = 0;
		String msg;       
	if(username == null || password == null){
		msg = "用户名和密码不能为空!";
		status = -1;
		json.put("msg", msg);
		json.put("status", status);
		return json;		
	}else if(username.equals("") || password.equals("")){
		msg = "用户名和密码不能为空!";
		status = -1;
		json.put("msg", msg);
		json.put("status", status);
		return json;		
	}else{
		//判断当前登录账号身份
		if(username.indexOf("admin")<0){
			//当username.indexOf("admin")返回值为-1，则说明当前登录身份为用户
			System.out.println("测试第一次登录密码："+password);
			password = EncryptUtil.getMD5String(password);
			YgUsers user = userService.userLogin(username,password);
			if(user != null){
				//将当前用户信息存储到Session中
				session.setAttribute("user", user);
				session.setAttribute("role", "user");
				//当前账号身份为用户
				msg = "登录成功!";
				status = 1;
				//返回当前用户基本信息给前端,将信息封装进map集合中
				Map<String,Object> users = new HashMap<>();
				users.put("username",user.getUsername());
				users.put("nickname",user.getNickname());
				users.put("monile",user.getMobile());
				users.put("email",user.getEmail());
				users.put("sex", user.getSex());
				json.put("user", users);
			    json.put("msg", msg);
			    json.put("status", status);
			    return json;
			}
		}else{
			//当username.indexOf("admin")返回值大于0，则说明当前登录身份为管理员
			//当user为null，则当前登录账号身份为管理员
			YgAdmins admin = adminService.adminLogin(username, password);
			if(admin != null){
				//将当前管理员信息存储到Session中
				session.setAttribute("admin", admin);
				session.setAttribute("role", "admin");
				msg = "登录成功!";
				status = 1;
				//返回当前用户基本信息给前端,将信息封装进map集合中
				Map<String,Object> admins = new HashMap<>();
				admins.put("username",admin.getUsername());
				admins.put("nickname",admin.getNickname());
				admins.put("powervalue",admin.getPowerValue());
				json.put("msg", msg);
			    json.put("admin", admins);
			    json.put("status", status);
			    return json;
         	}
		}
		msg = "用户名或密码输入错误!";
		status = -1;
		json.put("msg", msg);
		json.put("status", status);
		return json;	
	}
}
	
	/*
	 * 用户模块功能三、普通用户注册
	 * 接收studentTest1页面传递的参数
	 * 方法中要使用注解@Valid , 否则Map对象map中的值为null ， 实体类YgUsers中的注解校验将不起作用
	 */
	@RequestMapping(value ="/pc/register",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
//	public JSONObject register(@Valid @RequestBody Map<String,Object> maps, @Valid YgUsers user,BindingResult result){
	public JSONObject register(@Valid YgUsers user,String registerVerification,BindingResult result,HttpSession session){
		JSONObject json=new JSONObject();
		int status = 0;
		String msg;
		System.out.println("验证码测试：registerVerification:"+registerVerification);
		//调用工具类Validator中的方法，通过Validator类获取结果
		Map<String,Object> map = Validator.getValidator(result);
		//为null，则说明没有错误   
		if(map == null){
			//判断用户输入的验证码 与 邮箱中的验证码是否相同
			String rVerification = (String) session.getAttribute("registerVerification");
			System.out.println("session验证码测试：rVerification:"+rVerification);
			if(registerVerification.equals(rVerification)){
				//判断当前输入用户账号邮箱 与 验证码获取时邮箱是否相同
			 String rEmail = (String) session.getAttribute("rEmail");
				   if(user.getEmail().equals(rEmail)){
					   //对前端传输过来的密码，通过MD5码进行二次加密
					   String passwordjm = EncryptUtil.getMD5String(user.getPassword());
					   System.out.println("密码第二次加密："+passwordjm);
					   user.setPassword(passwordjm);
					   System.out.println("生成新的用户信息："+user);
					   //将注册的用户信息添加到数据库中
					   boolean results = userService.userRegisters(user);
					   if(results != false){
						   boolean resultx = userService.initUserWallet(user.getUid());
						   msg = "注册成功!";
			        	   status = 1;
			        	   json.put("msg", msg);
			        	   json.put("status", status);
			        	   return json;
					   }else{
						   msg = "注册信息错误,请重新注册!";
			        	   status = -1;
			        	   json.put("msg", msg);
			        	   json.put("status", status);
			        	   return json;
					   }
				   }else{
					   msg = "邮箱输入错误!";
		        	   status = -1;
		        	   json.put("msg", msg);
		        	   json.put("status", status);
		        	   return json; 
				   }
			}else{
				   msg = "验证码输入错误!";
	        	   status = -1;
	        	   json.put("msg", msg);
	        	   json.put("status", status);
	        	   return json;
			}
           }else{
        	   //不为null，则说明存在错误，获取错误信息，并打印
        	   msg = "注册信息错误!";
        	   status = -1;
        	   json.put("msg", msg);
        	   json.put("status", status);
        	   json.put("error", map);
        	   json.put("user", user);
        	   return json;
           }
	}
	
	
	/*
	 * 用户模块功能三、普通用户注册-获取验证码
	 */
	@RequestMapping(value ="/pc/registerverification",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject registerverification(@RequestBody Map<String,Object> map,HttpSession session){
		JSONObject json=new JSONObject();
		int status = 0;
		String msg;
	    // 测试获取的邮箱
		System.out.println("map:"+map);
		// 获取JSON串中的邮箱;
		String email = (String) map.get("email");
		// 判断当前注册邮箱是否已存在
		YgUsers users = this.userService.findUsersEmail(email);
		if(users == null){
			//users为null，说明当前邮箱没有注册过用户，执行邮箱发送
			this.userService.registeroutEmailVerification(email,session);
			//将用户第一次输入的邮箱进行session保存
			session.setAttribute("rEmail",email);
			status = 1;
			msg = "邮箱验证码发送成功";
			json.put("status", status);
			json.put("msg", msg);
			return json;
		}else{
     	   msg = "当前邮箱已注册!";
     	   status = -1;
     	   json.put("msg", msg);
     	   json.put("status", status);
     	   return json;
		}
		
	}
	
	
	/*
	 * 用户模块功能四、用户账号注销->向用户邮箱发送 6位数的随机数 验证码；
	 */
	@RequestMapping(value ="/pc/sendoutemail",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject sendOutEmail(HttpSession session) {
		// 实例化JSONObject对象
		JSONObject json = new JSONObject();
		int status = 0;
		String msg = "验证码获取失败";
		
		// 获取当前Session中该用户的Email；
		YgUsers users = (YgUsers) session.getAttribute("user");
		if (users != null) {
			// 调用发送邮箱方法
			this.userService.sendOutEmail(users,session);
			status = 1;
			msg = "验证码获取成功";
			json.put("status", status);
			json.put("msg", msg);
			return json;
		} else {
			status = -1;
			json.put("status", status);
			json.put("msg", msg);
			return json;
		}
	}
	
	/*
	 * 用户模块功能五、用户账号注销->判断当前用户输入的验证码是否正确，正确则执行delete()方法对当前账号进行注销；
	 */
	@RequestMapping(value ="/pc/delete",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject delete(@RequestBody Map<String,Object> map,HttpSession session) {
		// 实例化JSONObject对象
		JSONObject json = new JSONObject();
		int status = 0;
		String msg = "账号注销失败";
		//获取map集合中的json串
//		System.out.println("获取map集合中的json串：" + map);
		String veri = (String) map.get("verification");
		// 获取session中的验证码
		String verification = (String) session.getAttribute("verification");
//		System.out.println("获取session中的验证码：" + verification);
		//判断用户输入的验证码与邮箱中的验证码是否一致
		if(verification.equals(veri)){
			//获取当前用户账号的UUID,执行用户删除操作
			YgUsers users =  (YgUsers) session.getAttribute("user");
			String uuid = users.getUid();
//			System.out.println("获取session中的uuid：" + uuid);
			boolean result = this.userService.userDelete(uuid);
			if(result!=false){
				status = 1;
				msg = "账号注销成功";
				json.put("status", status);
				json.put("msg", msg);
				return json;
			}else{
				status = -1;
				msg = "账号注销失败";
				json.put("status", status);
				json.put("msg", msg);
				return json;
			}
		}else{
			status = -1;
			msg = "输入验证码错误";
			json.put("status", status);
			json.put("msg", msg);
			return json;
		}
		
	}
	
	/*
	 * 用户模块功能六、用户账号密码找回->判断当前用户输入邮箱是否正确，正确则执行方法将当前用户账号的密码发送到邮箱中；
	 */
	@RequestMapping(value ="/pc/findpassword",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject findpassword(@RequestBody Map<String,Object> map,HttpSession session) {
		// 实例化JSONObject对象
		JSONObject json = new JSONObject();
		int status = 0;
		String msg = "密码找回失败";
		//获取map集合中的json串
		System.out.println("获取map集合中的json串：" + map);
		String email = (String) map.get("email");
		//判断用户输入的验证码与邮箱中的验证码是否一致
		if(email.equals("")){
			status = -1;
			msg = "输入账号或邮箱不能为空";
			json.put("status", status);
			json.put("msg", msg);
			return json;
		}
		if(email != null){
			//获取当前用户账号、邮箱,执行查询操作
			YgUsers users =  this.userService.findYgUsersByUsernameAndEmail(email);
			if(users != null){
				//当前输入 用户账号 和 邮箱 正确
				this.userService.findPassowrd(users);
				status = 1;
				msg = "密码找回成功，请登录";
				json.put("status", status);
				json.put("msg", msg);
				return json;
			}else{
				status = -1;
				msg = "输入的账号或邮箱错误";
				json.put("status", status);
				json.put("msg", msg);
				return json;
			}
		}else{
			status = -1;
			msg = "输入账号或邮箱不能为空";
			json.put("status", status);
			json.put("msg", msg);
			return json;
		}
		
	}
	
	/*
	 * 用户模块功能七、用户修改密码->1、判断用户输入的两次新密码是否相同；2、判断用户的旧密码是否正确
	 */
	@RequestMapping(value ="/pc/updatepassword",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject updatePassword(@RequestBody Map<String,Object> map,HttpSession session) {
		// 实例化JSONObject对象
		JSONObject json = new JSONObject();
		int status = 0;
		String msg = "用户修改密码失败";
		// 获取map集合中的json串
		System.out.println("获取map集合中的json串：" + map);
		// 判断用户输入的两次新密码是否相同；（一次加密的密码）
		String x1_password = (String) map.get("x1_password");
		String x2_password = (String) map.get("x2_password");
		String id = (String) session.getAttribute("id");
		if(x1_password.equals(x2_password)){
			// 输入两次新密码相同，判断输入旧密码是否与数据库中密码匹配
			String password = (String) map.get("password");
			// 对旧密码进行二次MD5码加密
			password = EncryptUtil.getMD5String(password);
			// 将 二次MD5码加密旧密码 与数据库中 二次MD5码加密旧密码 进行查询
			YgUsers findUser = this.userService.findUsersPassword(id,password);
	//		System.out.println("测试当前用户账号："+findUser.getUsername());
			if(findUser != null){
				//输入旧密码正确，则对新密码进行二次MD5码加密，修改到数据库中；
				x1_password = EncryptUtil.getMD5String(x1_password);
				boolean result = this.userService.UsersUpdatePassword(x1_password,findUser.getUsername());
				if(result != false){
					status = 1;
					msg = "密码修改成功，请登录";
					json.put("status", status);
					json.put("msg", msg);
					return json;
				}else{
					status = -1;
					msg = "密码修改失败";
					json.put("status", status);
					json.put("msg", msg);
					return json;
				}
			}else{
				status = -1;
				msg = "输入旧密码错误";
				json.put("status", status);
				json.put("msg", msg);
				return json;
			}
		}else{
			status = -1;
			msg = "输入两次新密码不相同";
			json.put("status", status);
			json.put("msg", msg);
			return json;
		}
		
	}
	
	
	/*
	 * 用户模块功能三、普通用户注册
	 */
//	@RequestMapping("register")
//	@ResponseBody
//	public JSONObject register(String username,String password,HttpSession session){
//		JSONObject json=new JSONObject();
//		int status = 0;
//		String msg = "登录失败，请输入正确的账号或密码！";
//		YgUsers user = userService.userLogin(username, password);
//		//判断用户的账号与密码是否正确
//		if(user!=null){
//			status = 1;
//			msg = "登录成功";
//			json.put("user", user);
//			json.put("status", status);
//			json.put("msg", msg);
//			return json;
//		}else{
//			msg = "登录失败，请输入正确的账号或密码！";
//			return json;
//		}
//		
//	}
	

	
}
